package com.bitdf.txing.order.listener;

import com.bitdf.txing.common.to.mq.SeckillOrderTo;
import com.bitdf.txing.order.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author Lizhiwei
 * @date 2023/8/25 23:10:49
 * 注释：为秒杀成功的请求生成订单
 */
@RabbitListener(queues = "seckill.and.order.queue")
@Service
@Slf4j
public class DisposeSeckillResListener {
    @Autowired
    private OrderService orderService;

    /**
     * 为秒杀用户（走到这里说明已秒杀成功） 生成订单
     * @param orderTo
     * @param channel
     * @param message
     * @throws IOException
     */
    @RabbitHandler
    public void listener(SeckillOrderTo orderTo, Channel channel, Message message) throws IOException {
        log.info("收到秒杀结果（orderSn: {} skuId: {}）, 开始生成为其订单", orderTo.getOrderSn(), orderTo.getSkuId());
        try {
            boolean b = orderService.createSeckillOrder(orderTo);
            if (b) {
                log.info("成功生成订单");
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            } else {
                throw new RuntimeException();
            }
        } catch (Exception e) {
            log.info("生成订单失败：{}", orderTo.getOrderSn());
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
}
